import httpx
from typing import Optional, Dict, List
from pydantic import BaseModel
import logging
from config import settings

logger = logging.getLogger(__name__)


class OpenRouterRequest(BaseModel):
    model: str = settings.openrouter_model
    messages: List[Dict]
    temperature: float = 0.7
    max_tokens: Optional[int] = None


class OpenRouterClient:
    def __init__(self):
        self.base_url = settings.openrouter_base_url
        self.headers = {
            "Authorization": f"Bearer {settings.openrouter_key.get_secret_value()}",
            "HTTP-Referer": "https://mykb.com",
            "X-Title": "Personal Knowledge System"
        }

    async def chat_completion(self, request: OpenRouterRequest) -> Optional[Dict]:
        """调用OpenRouter API"""
        try:
            async with httpx.AsyncClient(timeout=30) as client:
                response = await client.post(
                    f"{self.base_url}/chat/completions",
                    json=request.dict(),
                    headers=self.headers
                )
                response.raise_for_status()

                return {
                    "content": response.json()["choices"][0]["message"]["content"],
                    "usage": response.json().get("usage", {}),
                    "cost": response.headers.get("x-openrouter-cost-credits", 0)
                }
        except Exception as e:
            logger.error(f"API调用失败: {str(e)}")
            return None